'use strict';

const { Service } = require('egg');
const crypto = require('crypto');
const COS = require('cos-nodejs-sdk-v5');
const STS = require('qcloud-cos-sts');
const region = 'ap-chengdu';
const defaultBucketName = 'kujomiva';
const appid = '1259361798';
const SecretId = 'AKIDyoCTgmOT6ZuhKofFCA1meOxSnGgwhzoR';
const SecretKey = 'rdEev3FF8mDWfiaLj6IJAqNn8uBMNGyV';

// 转为promise函数
async function promisify(fn, receiver) {
    return (...args) => {
        return new Promise((resolve, reject) => {
            fn.apply(receiver, [...args, (err, res) => {
                return err ? reject(err) : resolve(res);
            }]);
        });
    };
}
function md5(param) {
    return crypto.createHash('md5').update(param).digest('hex');
}

class ServiceCOS extends Service {
    // 设置临时密钥
    async sts({ BucketName = defaultBucketName } = {}) {
        const scope = [{
            action: [
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ],
            bucket: `${BucketName}-${appid}`,
            region,
            prefix: '*'
        }];
        const getCredential = await promisify(STS.getCredential, STS);
        const policy = STS.getPolicy(scope);
        return await getCredential({
            secretId: SecretId,
            secretKey: SecretKey,
            durationSeconds: 7200,
            region,
            policy
        }).then(res => {
            return res;
        }).catch(err => {
            return err;
        });
    }
    // 简单上传
    async putObject({ stream, BucketName = 'kujomiva', folder = 'default', progressFun = _ => { } }) {
        const cos = new COS({
            SecretId,
            SecretKey
        });
        const suffix = stream.filename.slice(stream.filename.lastIndexOf('.'));
        const putObject = await promisify(cos.putObject, cos);
        return await putObject({
            Bucket: `${BucketName}-${appid}`,
            Region: region,
            Key: `${folder}/${md5(JSON.stringify(stream))}${suffix}`,
            Body: stream,
            onProgress: progressData => progressFun(progressData)
        }).then(res => {
            return res;
        }).catch(err => {
            return err;
        });
    }
    // 删除文件
}

module.exports = ServiceCOS;

